package com.apes.scm.demo.service;

import com.apes.framework.plugin.cache.Cache;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.LockUtil;
import com.apes.framework.api.SpringManager;
import com.apes.oap.annotation.IgnoreSignType;
import com.apes.oap.annotation.NeedInSessionType;
import com.apes.oap.annotation.ServiceMethod;
import com.apes.oap.annotation.ServiceMethodBean;
import com.apes.oap.response.OapResponse;
import com.apes.scm.demo.model.Person1;
import com.apes.scm.demo.repository.Person1Repository;
import com.apes.scm.demo.request.LogonRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;

/**
 * 功能：服务测试
 *
 * @author xul
 * @create 2017-11-17 8:58
 */
@ServiceMethodBean(version = "1.0", needInSession = NeedInSessionType.NO)
public class PersonService {
    private static Logger log = LoggerFactory.getLogger(PersonService.class);

    @Autowired
    private Cache cache;

    @Transactional()
    @ServiceMethod(method = "person.logon")
    public OapResponse<Person1> logon(LogonRequest request) {
        Person1Repository repository = SpringManager.getBean(Person1Repository.class);
        Person1 user = new Person1("userName");
        user = repository.save(user);
        return new OapResponse<Person1>().setBody(user);
    }

    @Autowired
    private LockUtil lockUtil;
    /**
     * 功能：事务传递性测试(aut => aut)
     */
    @Transactional()
    @ServiceMethod(method = "person.save", ignoreSign = IgnoreSignType.YES) //, ignoreSign = IgnoreSignType.YES
    public OapResponse<?> save(SimpleRequest request) {
        Lock lock = lockUtil.getDistributedLock("test");
        lock.lock();// 得到锁
        try {
            Person1Repository repository = SpringManager.getBean(Person1Repository.class);
            Person1 user = new Person1("userName");
            repository.save(user);
            AppSecretService service = SpringManager.getBean(AppSecretService.class);
            cache.put("test", "hello xul!");
            System.out.println(cache.get("test"));

            return service.save(request);
        } finally {
            lock.unlock();// 释放锁
        }
    }

    public OapResponse send(SimpleRequest request) {

        List<Map> rows = new ArrayList();
        for (int i = 0; i < 1000; i++) {
            Map row = new HashMap();
            row.put("body", i);
            rows.add(row);
        }
        return new OapResponse().setBody(rows);
    }

}
